/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.sys.dao.SysRoleDao;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.dao.SysUserRoleDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.form.MyRegisterForm;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleDao sysRoleDao;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Long createUserId = (Long)params.get("createUserId");

		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			new QueryWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
				.eq(createUserId != null,"create_user_id", createUserId)
		);

		List<SysUserEntity> records = page.getRecords();
		//List<Long> userIds = records.stream().map(item -> item.getUserId()).collect(Collectors.toList());

		List<SysUserRoleEntity> sysUserRoleEntities = sysUserRoleDao.selectList(null);
		List<Long> roleUserIds = sysUserRoleEntities.stream().map(item -> item.getUserId()).collect(Collectors.toList());
		List<SysUserEntity> lists = new ArrayList<>();

		for (SysUserEntity userEntity:records){
			boolean isContains = roleUserIds.contains(userEntity.getUserId());
			if (!isContains){
				continue;
			}
			List<SysUserRoleEntity> userRoleEntity = sysUserRoleEntities.stream().filter(item -> item.getUserId() == userEntity.getUserId()).collect(Collectors.toList());
			SysUserRoleEntity sysUserRoleEntity = userRoleEntity.get(0);

			if (sysUserRoleEntity.getRoleId().equals(RoleCode.SUPER_ADMIN) ||
			sysUserRoleEntity.getRoleId().equals(RoleCode.SUB_ADMIN) ||
			sysUserRoleEntity.getRoleId().equals(RoleCode.HUNTING_ROLE)){
				lists.add(userEntity);
			}
		}
		page.setRecords(lists);
		page.setSize(lists.size());

		return new PageUtils(page);
	}

	@Override
	public boolean register(MyRegisterForm form) {
		//拿到刚才注册的用户Id
		Long userId = registerProcess(form);

		//企业级用户注册
		if ("3".equals(form.getCompanyOrPerson())){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(RoleCode.COMPANY_ROLE);
			boolean save = sysUserRoleService.save(sysUserRoleEntity);
			if (save){
				return true;
			}
		}else if ("2".equals(form.getCompanyOrPerson())){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(RoleCode.PERSONAL_ROLE);
			boolean save = sysUserRoleService.save(sysUserRoleEntity);
			if (save){
				return true;
			}
		}
		return false;
	}


	private Long registerProcess(MyRegisterForm form){

		QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("username",form.getUsername());
		SysUserEntity userEntity = sysUserDao.selectOne(wrapper);
		if (!(form.getPassword().equals(form.getRepassword()))){
			throw new RRException("两次密码不一致",MyStatusCode.TWO_PASSWORD_NOT_SOME);
		}

		if (userEntity!=null){
			throw new RRException("此用户名已经被注册",MyStatusCode.HAVE_REGISTER_COUNT);
		}
		String salt = RandomStringUtils.randomAlphanumeric(20);
		SysUserEntity sysUserEntity = new SysUserEntity();

		sysUserEntity.setUsername(form.getUsername());
		//sysUserEntity.setPassword(DigestUtils.sha256Hex(form.getPassword()));
		sysUserEntity.setPassword(new Sha256Hash(form.getPassword(), salt).toHex());
		sysUserEntity.setSalt(salt);
		sysUserEntity.setMobile(form.getMobile());
		sysUserEntity.setEmail(form.getEmail());
		sysUserEntity.setCreateTime(new Date());
		sysUserEntity.setStatus(1);

		int insert = sysUserDao.insert(sysUserEntity);
		System.out.println("UserId === >>>"+sysUserEntity.getUserId());

		if (insert<=0){
			throw new RRException("用户注册失败，请联系管理员",MyStatusCode.USER_REGISTER_FAIL);
		}
		return sysUserEntity.getUserId();
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void saveUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public int update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        return 0;
    }

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}